package com.atguigu.edu.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.utils.DateFormatUtil;
import com.atguigu.edu.realtime.utils.MyKafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author xz
 * @date 2022/11/18
 * 日志分流
 */
public class DwdTrafficBaseLogSplit {
    public static void main(String[] args) throws Exception {
        //TODO 1 流执行环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
        //TODO 2 检查点相关配置
        /*//2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 设置job取消之后，检查点是否保留
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
        //2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop101:8020/edu/ck");
        //2.7 设置操作hadoop的用户
        System.setProperty("HADOOP_USER_NAME","atguigu");*/
        //TODO 3 从kafka topic_log主题读取数据
        String topic = "topic_log";
        String groupId = "dwd_traffic_log_split_group";
        DataStreamSource<String> kfStrDS = env.addSource(MyKafkaUtil.getKafkaConsumer(topic, groupId));
        kfStrDS.print();
        //TODO 4 进行类型转换 jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kfStrDS.map(jsonStr -> JSON.parseObject(jsonStr));
        jsonObjDS.print(">");
        //TODO 5 根据mid进行分组
        KeyedStream<JSONObject, String> keyedByMidDS = jsonObjDS.keyBy(r -> r.getJSONObject("common").getString("mid"));
        //TODO 6 使用状态编程对新老用户信息进行修复
        SingleOutputStreamOperator<JSONObject> isNewDS = keyedByMidDS.map(
                new RichMapFunction<JSONObject, JSONObject>() {
                    private ValueState<String> lastVisitDateState;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("split-last-visit-date", String.class);
                        lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                    }

                    @Override
                    public JSONObject map(JSONObject jsonObj) throws Exception {
                        String isNew = jsonObj.getJSONObject("common").getString("is_new");
                        String lastVisitDate = lastVisitDateState.value();
                        Long ts = jsonObj.getLong("ts");
                        String curVisitDate = DateFormatUtil.toDate(ts);
                        if ("1".equals(isNew)){
                            if (StringUtils.isEmpty(lastVisitDate)){
                                lastVisitDateState.update(curVisitDate);
                            }else {
                                if (!curVisitDate.equals(lastVisitDate)){
                                    isNew = "0";
                                    jsonObj.getJSONObject("common").put("is_new",isNew);
                                }
                            }
                        }
                        //如果标记不是新用户
                        else {
                            if (StringUtils.isEmpty(lastVisitDate)){
                                String yesterday = DateFormatUtil.toDate(ts - 24 * 3600 * 1000);
                                lastVisitDateState.update(yesterday);
                            }
                        }
                        return jsonObj;
                    }
                }
        );
        isNewDS.print(">>");
        //TODO 7 按照日志类型进行分流  错误日志-错误侧输出流 启动日志-启动侧输出流 曝光日志-曝光侧输出流 动作日志-动作侧输出流 页面日志-主流
        //6.1 定义侧输出流标签
        OutputTag<String> errTag = new OutputTag<String>("errTag") {};
        OutputTag<String> startTag = new OutputTag<String>("startTag") {};
        OutputTag<String> displayTag = new OutputTag<String>("displayTag") {};
        OutputTag<String> actionTag = new OutputTag<String>("actionTag") {};
        OutputTag<String> appVideoTag = new OutputTag<String>("appVideoTag") {};
        //6.2 分流
        SingleOutputStreamOperator<String> pageDS = isNewDS.process(
                new ProcessFunction<JSONObject, String>() {
                    @Override
                    public void processElement(JSONObject jsonObj, Context ctx, Collector<String> out) throws Exception {
                        JSONObject errJsonObj = jsonObj.getJSONObject("err");
                        if (errJsonObj != null) {
                            //将错误日志  保存到错误侧输出流
                            ctx.output(errTag, jsonObj.toJSONString());
                            jsonObj.remove("err");
                        }

                        JSONObject startJsonObj = jsonObj.getJSONObject("start");
                        JSONObject appVideoJsonObj = jsonObj.getJSONObject("appVideo");
                        if (startJsonObj != null) {
                            //启动日志  保存到启动侧输出流
                            ctx.output(startTag, jsonObj.toJSONString());
                        }
                        else if (appVideoJsonObj!=null){
                            //视频播放日志 保存到视频播放侧输出流
                            ctx.output(appVideoTag, jsonObj.toJSONString());
                        }
                        else {
                            //页面日志
                            JSONObject commonJsonObj = jsonObj.getJSONObject("common");
                            JSONObject pageJsonObj = jsonObj.getJSONObject("page");
                            Long ts = jsonObj.getLong("ts");

                            //判断是否在页面上存在曝光信息
                            JSONArray displayArr = jsonObj.getJSONArray("displays");
                            if (displayArr != null && displayArr.size() > 0) {
                                //遍历所有的曝光数据
                                for (int i = 0; i < displayArr.size(); i++) {
                                    JSONObject displayJsonObj = displayArr.getJSONObject(i);
                                    //定义一个新的json对象，用于封装每一天曝光数据
                                    JSONObject newDisplayJsonObj = new JSONObject();
                                    newDisplayJsonObj.put("common", commonJsonObj);
                                    newDisplayJsonObj.put("page", pageJsonObj);
                                    newDisplayJsonObj.put("ts", ts);
                                    newDisplayJsonObj.put("display", displayJsonObj);
                                    //将曝光数据放到曝光侧输出流中
                                    ctx.output(displayTag, newDisplayJsonObj.toJSONString());
                                }
                                jsonObj.remove("displays");
                            }

                            //判断是否在页面上存在动作信息
                            JSONArray actionArr = jsonObj.getJSONArray("actions");
                            if (actionArr != null && actionArr.size() > 0) {
                                for (int i = 0; i < actionArr.size(); i++) {
                                    JSONObject actionJsonObj = actionArr.getJSONObject(i);
                                    //创建一个新的json对象，用于封装每一条动作日志
                                    JSONObject newActionJsonObj = new JSONObject();
                                    newActionJsonObj.put("common", commonJsonObj);
                                    newActionJsonObj.put("page", pageJsonObj);
                                    newActionJsonObj.put("action", actionJsonObj);
                                    //将动作数据放到动作侧输出流中
                                    ctx.output(actionTag, newActionJsonObj.toJSONString());
                                }
                                jsonObj.remove("actions");
                            }

                            //将页面日志放到主流中
                            out.collect(jsonObj.toJSONString());
                        }
                    }
                }
        );
        //TODO 7.将不同流中的数据写到kafka的不同的主题中
        DataStream<String> errDS = pageDS.getSideOutput(errTag);
        DataStream<String> startDS = pageDS.getSideOutput(startTag);
        DataStream<String> displayDS = pageDS.getSideOutput(displayTag);
        DataStream<String> actionDS = pageDS.getSideOutput(actionTag);
        DataStream<String> appVideoDS = pageDS.getSideOutput(appVideoTag);

        pageDS.print(">>>");
        errDS.print("@@@");
        startDS.print("###");
        displayDS.print("$$$");
        actionDS.print("&&&");
        appVideoDS.print("xxx");

        pageDS.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_page_log"));
        errDS.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_err_log"));
        startDS.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_start_log"));
        displayDS.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_display_log"));
        actionDS.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_action_log"));
        appVideoDS.addSink(MyKafkaUtil.getKafkaProducer("dwd_traffic_appVideo_log"));

        env.execute();
    }
}
